<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="100px">
      <el-form-item label="所属线路" prop="busLineId">
        <el-select v-model="queryParams.busLineId" clearable placeholder="请选择所属线路">
          <el-option
            v-for="dict in busLineList"
            :key="dict.id"
            :label="dict.busLineName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="站点名称" prop="stationName">
        <el-input
          v-model="queryParams.stationName"
          placeholder="请输入站点名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="上行下行" prop="upDown">
        <el-select v-model="queryParams.upDown" clearable placeholder="请选择上行下行">
          <el-option
            v-for="dict in stationUpDown"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="公交车站类型" prop="startEndType">
        <el-select v-model="queryParams.startEndType" clearable placeholder="请选择公交车站类型">
          <el-option
            v-for="dict in busStationType"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否主要站点" prop="isMainStation">
        <el-select v-model="queryParams.isMainStation" clearable placeholder="是否主要站点">
          <el-option
            v-for="dict in mainSite"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="tableList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="站点名称" align="center" prop="stationName" />
      <el-table-column label="上行下行" align="center" prop="upDown">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bhxq_station_up_down" :value="scope.row.upDown" />
        </template>
      </el-table-column>
      <el-table-column label="公交车站类型" align="center" prop="startEndType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bhxq_station_type" :value="scope.row.startEndType" />
        </template>
      </el-table-column>
      <el-table-column label="站点标志" align="center" prop="siteLogo">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bhxq_station_site_logo" :value="scope.row.siteLogo" />
        </template>
      </el-table-column>
      <el-table-column label="是否主要站点" align="center" prop="isMainStation">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bhxq_common_on_off" :value="scope.row.isMainStation" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleexamine(scope.row)"
          >查询</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改公交站点对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="站点名称" prop="stationName">
              <el-input v-model="form.stationName" :disabled="disabledon" placeholder="请输入站点名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="上行下行" prop="upDown">
              <el-select v-model="form.upDown" :disabled="disabledon" placeholder="请选择上行下行" style="width: 100%">
                <el-option
                  v-for="dict in stationUpDown"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="公交车站类型" prop="startEndType">
              <el-select v-model="form.startEndType" :disabled="disabledon" placeholder="请选择公交车站类型" style="width: 100%">
                <el-option
                  v-for="dict in busStationType"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="站点标志" prop="siteLogo">
              <el-select v-model="form.siteLogo" :disabled="disabledon" placeholder="请选择站点标志" style="width: 100%">
                <el-option
                  v-for="dict in siteLogoList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否主要站点" prop="isMainStation">
              <el-select v-model="form.isMainStation" :disabled="disabledon" placeholder="是否主要站点" style="width: 100%">
                <el-option
                  v-for="dict in mainSite"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所在道路名" prop="roadName">
              <el-input v-model="form.roadName" :disabled="disabledon" placeholder="请输入所在道路名" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="产权归属" prop="propertyOwner">
              <el-input v-model="form.propertyOwner" :disabled="disabledon" placeholder="请输入产权归属" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供电方式" prop="powerSupplyMode">
              <el-input v-model="form.powerSupplyMode" :disabled="disabledon" placeholder="请输入供电方式" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="占地面积" prop="landArea">
              <!--              <el-input v-model="form.landArea" placeholder="请输入占地面积" />-->
              <el-input-number v-model="form.landArea" :disabled="disabledon" :precision="2" :step="1" size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="建筑面积" prop="buildingArea">
              <!--              <el-input v-model="form.buildingArea" placeholder="请输入建筑面积" />-->
              <el-input-number v-model="form.buildingArea" :disabled="disabledon" :precision="2" :step="1" size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="8" />
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="具体位置：" prop="specificLocation">
              <el-autocomplete
                v-model="form.specificLocation"
                :disabled="disabledon"
                :fetch-suggestions="querySearchAsync"
                :trigger-on-focus="false"
                clearable
                placeholder="请先搜索地址"
                style="width: 100%"
                @select="handleSelect"
              >
                <template slot-scope="{ item }">
                  <i class="el-icon-search fl mgr10" />
                  <div style="overflow: hidden">
                    <div class="title">{{ item.title }}</div>
                    <span class="address ellipsis">{{ item.address }}</span>
                  </div>
                </template>
              </el-autocomplete>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8" :offset="1">
            <el-form-item label="经度" prop="longitude">
              <el-input v-model="form.longitude" :disabled="disabledon" placeholder="请输入经度" />
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="1">
            <el-form-item label="维度" prop="latitude">
              <el-input v-model="form.latitude" :disabled="disabledon" placeholder="请输入维度" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="地图定位：">
              <div id="map-container" style="width: 100%; height: 300px" />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="disabledon == false" type="primary" v-no-more-click @click="submitForm">确 定</el-button>
        <el-button v-if="disabledon == false && title !== '修改站点'" v-no-more-click type="primary" @click="submitForm('ContinueFill')">确定并继续填写</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { listBusStation, getBusStation, delBusStation, addBusStation, updateBusStation } from '@/api/bhxq/busStation'
// import { listAllBusLine } from '@/api/bhxq/busLine'

// 引入第三方工具包
import loadBMap from '@/api/bhxq/loadBMap.js'
import {
  addBusStation,
  delBusStation,
  getBusStation, getInfo,
  listAllBusLine,
  listBusStation,
  updateBusStation
} from '@/api/informationReport'

export default {
  name: 'Index',
  dicts: ['bhxq_station_up_down', 'bhxq_station_type', 'bhxq_common_on_off', 'bhxq_station_site_logo'],
  data() {
    return {
      disabledon: true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 公交站点表格数据
      tableList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stationName: null,
        lineName: null,
        upDown: null,
        startEndType: null,
        isMainStation: null
      },
      // 上行下行字典
      stationUpDown: [
        {
          label: '下行',
          value: '0'
        },
        {
          label: '上行',
          value: '1'
        }
      ],
      // 公交车站类型字典
      busStationType: [
        {
          label: '首战',
          value: '1'
        },
        {
          label: '中途站',
          value: '2'
        },
        {
          label: '末站',
          value: '3'
        }
      ],
      // 是否主要站点字典
      mainSite: [
        {
          label: '否',
          value: '0'
        },
        {
          label: '是',
          value: '1'
        }
      ],
      // 站点标志字典
      siteLogoList: [
        {
          label: '站亭',
          value: '1'
        },
        {
          label: '站箱',
          value: '2'
        },
        {
          label: '站牌',
          value: '3'
        }
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        stationName: [
          { required: true, message: '站点名称不能为空', trigger: 'blur' }
        ],
        lineName: [
          { required: true, message: '所属线路不能为空', trigger: 'blur' }
        ],
        // longitude: [
        //   { required: true, message: '经度不能为空', trigger: 'blur' }
        // ],
        // latitude: [
        //   { required: true, message: '维度不能为空', trigger: 'blur' }
        // ],
        upDown: [
          { required: true, message: '上下行不能为空', trigger: 'change' }
        ],
        roadName: [
          { required: true, message: '所在道路名不能为空', trigger: 'blur' }
        ],
        style: [
          { required: true, message: '样式不能为空', trigger: 'blur' }
        ],
        propertyOwner: [
          { required: true, message: '产权归属不能为空', trigger: 'blur' }
        ],
        // powerSupplyMode: [
        //   { required: true, message: '供电方式不能为空', trigger: 'blur' }
        // ],
        specificLocation: [
          { required: true, message: '具体位置不能为空', trigger: 'blur' }
        ],
        isGrounding: [
          { required: true, message: '是否做落地不能为空', trigger: 'blur' }
        ],
        // landArea: [
        //   { required: true, message: '占地面积不能为空', trigger: 'blur' }
        // ],
        // buildingArea: [
        //   { required: true, message: '建筑面积不能为空', trigger: 'blur' }
        // ],
        // startEndType: [
        //   { required: true, message: '公交车站类型不能为空', trigger: 'change' }
        // ],
        // siteLogo: [
        //   { required: true, message: '站点标志不能为空', trigger: 'change' }
        // ],
        stationNum: [
          { required: true, message: '中途站序号不能为空', trigger: 'blur' }
        ],
        isMainStation: [
          { required: true, message: '是否主要站点不能为空', trigger: 'change' }
        ]
      },
      busLineList: []
    }
  },
  created() {
    this.getListAllBusLine()
    this.getList()
  },
  mounted() {
    // 页面加载完之后，加载百度地图
    // 加载引入BMap
    loadBMap('https://api.map.baidu.com/api?v=3.0&ak=Fb93ekp4f6yLbTbE2vXjaV3WQm29CIe9')
  },
  methods: {
    // 加载地图方法
    getbaidu() {
      this.initMapeq = setInterval(() => {
        if (this.initMap()) {
          clearInterval(this.initMapeq)
        }
      })
    },
    // 百度地图封装方法
    // 初始化地图
    initMap() {
      try {
        var that = this
        // 1、挂载地图
        // 创建地图实例
        this.map = new BMap.Map('map-container')
        // 设置中心经纬度
        var point = new BMap.Point(
          this.form.longitude || 117.71739451779443,
          this.form.latitude || 39.009415913825386
        )

        // 3.在创建地图实例后，我们需要对其进行初始化，BMapGL.Map.centerAndZoom()方法要求设置中心点坐标和地图级别。 地图必须经过初始化才可以执行其他操作
        this.map.centerAndZoom(point, 14)
        // 滚轮缩放
        this.map.enableScrollWheelZoom()
        // 3、设置图像标注并绑定拖拽标注结束后事件
        this.mk = new BMap.Marker(point, { enableDragging: true })
        this.map.addOverlay(this.mk)
      } catch (err) {
        return false
      }
      // 4、添加（右上角）平移缩放控件
      this.map.addControl(
        new BMap.NavigationControl({
          anchor: BMAP_ANCHOR_TOP_RIGHT,
          type: BMAP_NAVIGATION_CONTROL_SMALL
        })
      )
      // 7、绑定点击地图任意点事件
      this.map.addEventListener('click', function(e) {
        console.log('点击了', e)
        that.getAddrByPoint(e.point)
      })
      return true
    },
    // 2、逆地址解析函数 根据坐标点获取详细地址  point   百度地图坐标点，必传
    getAddrByPoint(point) {
      var that = this
      var geco = new BMap.Geocoder()
      geco.getLocation(point, function(res) {
        // console.log(res);
        that.mk.setPosition(point)
        that.map.panTo(point)
        that.form.specificLocation = res.address
        that.form.longitude = res.point.lng
        that.form.latitude = res.point.lat
      })
    },
    // 8-1、地址搜索
    querySearchAsync(str, cb) {
      // 根据状态码
      var options = {
        onSearchComplete: function(res) {
          var s = []
          if (local.getStatus() == BMAP_STATUS_SUCCESS) {
            for (var i = 0; i < res.getCurrentNumPois(); i++) {
              s.push(res.getPoi(i))
            }
            cb(s)
          } else {
            cb(s)
          }
        }
      }
      var local = new BMap.LocalSearch(this.map, options)
      local.search(str)
    },
    // 8-2、选择地址
    handleSelect(item) {
      this.form.specificLocation = item.address + item.title
      // console.log(item);
      this.form.longitude = item.point.lng
      this.form.latitude = item.point.lat

      // console.log('lng', item.point.lng)
      // console.log('lat', item.point.lat)
      this.map.clearOverlays()
      this.mk = new BMap.Marker(item.point)
      this.map.addOverlay(this.mk)
      this.map.panTo(item.point)
    },

    /** 查询公交站点列表 */
    getList() {
      this.loading = true
      listBusStation(this.queryParams).then(response => {
        this.tableList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        stationName: null,
        lineName: null,
        longitude: null,
        latitude: null,
        upDown: null,
        roadName: null,
        style: null,
        propertyOwner: null,
        powerSupplyMode: null,
        specificLocation: null,
        isGrounding: null,
        landArea: null,
        buildingArea: null,
        startEndType: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
        siteLogo: null,
        stationNum: null,
        isMainStation: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      // 加载地图
      this.getbaidu()
      this.disabledon = false
      this.open = true
      this.title = '新增站点'
    },
    /** 查看按钮操作 */
    handleexamine(row) {
      this.reset()
      getBusStation(row.id).then(response => {
        this.form = response.data
        this.disabledon = true
        this.open = true
        this.title = '查看站点'
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getBusStation(id).then(response => {
        this.form = response.data
        this.disabledon = false
        // 加载地图
        this.getbaidu()
        this.open = true
        this.title = '修改站点'
      })
    },
    /** 提交按钮 */
    submitForm(type) {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateBusStation(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addBusStation(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              // 当点击确认确定并继续填写时 模态框不关闭
              if (type === 'ContinueFill') {
                this.reset()
                this.open = true
              } else {
                this.open = false
              }
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除站点名称为"' + row.stationName + '"的数据项？').then(function() {
        return delBusStation(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('bhxq/busStation/export', {
        ...this.queryParams
      }, `busStation_${new Date().getTime()}.xlsx`)
    },
    /** 查询公交站点列表 */
    getListAllBusLine() {
      this.loading = true
      listAllBusLine().then(response => {
        this.busLineList = response.data
      })
    }
  }
}
</script>
